package cn.wh.builder;

import cn.wh.mapping.MappedStatement;
import cn.wh.mapping.ResultMap;
import cn.wh.mapping.SqlCommandType;
import cn.wh.mapping.SqlSource;
import cn.wh.scripting.LanguageDriver;
import cn.wh.session.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author wh
 * @Description
 * @Date 2023/6/21 14:58
 * @Version 1.0
 **/
public class MapperBuilderAssistant extends BaseBuilder {

    private String currentNamespace;

    private String resource;

    public MapperBuilderAssistant(Configuration configuration, String resource) {
        super(configuration);
        this.resource = resource;
    }

    public String getCurrentNamespace() {
        return currentNamespace;
    }

    public void setCurrentNamespace(String currentNamespace) {
        this.currentNamespace = currentNamespace;
    }

    public String applyCurrentNamespace(String base, boolean isReference) {
        if (base == null) {
            return null;
        }
        if (isReference) {
            if (base.contains(".")) return base;
        }
        return currentNamespace + "." + base;
    }

    public MappedStatement addMappedStatement(
            String id,
            SqlSource sqlSource,
            SqlCommandType sqlCommandType,
            Class<?> parameterType,
            String resultMap,
            Class<?> resultType,
            LanguageDriver lang) {

        id = applyCurrentNamespace(id, false);
        MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, id, sqlCommandType, sqlSource, resultType);
        //结果映射 给MappedStatement # resultMaps
        setStatementResultMap(resultMap, resultType, statementBuilder);

        MappedStatement statement = statementBuilder.build();
        // 映射语句气息 建造完存放到配置项中
        configuration.addMappedStatement(statement);
        return statement;
    }


    private void setStatementResultMap(
            String resultMap,
            Class<?> resultType,
            MappedStatement.Builder statementBuilder
    ) {
        //因为暂时没有 Mapper XML 中配置的 Map 返回结果 所以这里返回是null
        resultMap = applyCurrentNamespace(resultMap, true);

        List<ResultMap> resultMaps = new ArrayList<>();
        if (resultMap != null) {
            //TODO  暂无Map 结果映射配置 本章节不添加此逻辑
        } else if (resultType != null) {
            ResultMap.Builder inlineResultMapBuilder = new ResultMap.Builder(
                    configuration,
                    statementBuilder.id() + "-Inline",
                    resultType,
                    new ArrayList<>()
            );
            resultMaps.add(inlineResultMapBuilder.build());
        }
        statementBuilder.resultMaps(resultMaps);

    }


}
